#include "CommandParser.h"

CommandParser::CommandParser() {
	this->command = UNKNOWN;
}

Command CommandParser::getCommand() {
	return this->command;
}

string CommandParser::getCommandString() {
	return this->commandString;
}

list<string> CommandParser::getParameters() {
	return this->parameters;
}

bool CommandParser::parse(string line) {
	bool validLine = true;
	this->command = UNKNOWN;
	this->parameters.clear();
	string parameters = "";

	if ((line.find("share ") == 0) && (line.length() > 6)) {
		this->command = SHARE;
		this->commandString = "share";
		parameters = line.substr(6);
	} else if (line == "list") {
		this->command = LIST;
		this->commandString = "list";
	} else if (line == "list -m") {
		this->command = LIST;
		this->commandString = "list";
		parameters = line.substr(5);
	} else if ((line.find("download ") == 0) && (line.length() > 9)) {
		this->command = DOWNLOAD;
		this->commandString = "download";
		parameters = line.substr(9);
	} else if (line == "help") {
		this->command = HELP;
		this->commandString = "help";
	} else if (line == "exit") {
		this->command = EXIT;
		this->commandString = "exit";
	} else {
		validLine = false;
	}

	if (validLine) {
	    istringstream iss(parameters);
	    list<string> tokens;
	    tokens.clear();

	    // Itero sobre el string y guardo las "palabras" en un array dinamico.
	    copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter< list<string> >(tokens));

	    this->parameters = tokens;
	}

	return validLine;
}

CommandParser::~CommandParser () {
}
